#include "MyCustomPlot.h"
#include <QWheelEvent>

#include <QApplication>
#include <QPushButton>
#include <QWheelEvent>
#include <QCoreApplication>

#include <QDebug>

MyCustomPlot::MyCustomPlot(QWidget *parent):QCustomPlot(parent)
{

    /*
    // 创建竖线，初始时不显示
    verticalLine = new QCPItemLine(this);
    verticalLine->setVisible(false);
    verticalLine->setPen(QPen(Qt::black, 1)); // 设置线的颜色和宽度
    // 设置竖线的起点和终点
    verticalLine->start->setCoords(5, -10); // 设置起点坐标 (x, y)，这里 y 的值可以随意设置，因为竖线是垂直的
    verticalLine->end->setCoords(5, 10);   // 设置终点坐标 (x, y)

    // 设置竖线的样式，例如颜色和线宽
    verticalLine->setPen(QPen(Qt::red, 2));

    // 将竖线添加到 QCustomPlot 控件
    this->addItem(verticalLine);
//    this->registerItem(verticalLine);

    // 重新绘制 QCustomPlot 控件以显示竖线
    this->replot();
    */


    // 假设你已经有了一个QCustomPlot对象，名为customPlot
//    QCustomPlot *customPlot = new QCustomPlot();

    /*
    // 添加一个新的图表
    QCPGraph *graph = this->addGraph();

    // 设置图表的样式为竖线图
    graph->setLineStyle(QCPGraph::lsImpulse);
    graph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssNone, Qt::red, Qt::red, 5));

    // 添加数据点到图表中
    // 这里假设我们添加了五个竖线，每个竖线的x坐标相同，y坐标不同
    double x = 1.0;
    double y[5] = {2.0, 3.0, 4.0, 5.0, 6.0};
    for (int i = 0; i < 5; ++i) {
        graph->addData(x, y[i]);
    }

    // 重绘QCustomPlot以显示图表
    this->replot();
    */


    //在需要捕捉触屏的控件中增加
    setAttribute(Qt::WA_AcceptTouchEvents);
    setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);

    // 创建QFont并设置字体大小


    action1 = new QAction("放大", this);
    action2 = new QAction("缩小", this);
//    action3 = new QAction("Button 3", this);
//    action4 = new QAction("Button 4", this);

    // 创建QFont并设置字体大小
    QFont font1 =  action1->font();
    font1.setPointSize(13); // 设置字体大小为12
    action1->setFont(font1);

    // 创建QFont并设置字体大小
    QFont font2 =  action2->font();
    font2.setPointSize(13); // 设置字体大小为12
    action2->setFont(font2);


//    // 创建QFont并设置字体大小
//    QFont font3 =  action3->font();
//    font3.setPointSize(13); // 设置字体大小为12
//    action3->setFont(font3);

//    // 创建QFont并设置字体大小
//    QFont font4 =  action4->font();
//    font4.setPointSize(13); // 设置字体大小为12
//    action4->setFont(font4);

    // 将动作添加到菜单中
    menu = new QMenu(this);
    menu->addAction(action1);
    menu->addAction(action2);
//    menu->addAction(action3);
//    menu->addAction(action4);

    // 连接信号和槽
    connect(action1, &QAction::triggered, this, &MyCustomPlot::onActionTriggered1);
    connect(action2, &QAction::triggered, this, &MyCustomPlot::onActionTriggered2);
//    connect(action3, &QAction::triggered, this, &MyCustomPlot::onActionTriggered3);
//    connect(action4, &QAction::triggered, this, &MyCustomPlot::onActionTriggered4);

    CollectTimePre = QDateTime::currentDateTime();

}

//void MyCustomPlot::mouseMoveEvent(QMouseEvent *event)
//{
//    QCustomPlot::mouseMoveEvent(event); // 调用基类的mouseMoveEvent以保持原有功能



//}

void MyCustomPlot::mouseDoubleClickEvent(QMouseEvent *event)
{
    /********双击自适应***************
    rescaleAxes(true);
    shrinkView(1.2);
    replot();
    ********双击自适应***************/

    this->yAxis->setRange(-1,11);

    QCustomPlot::mouseDoubleClickEvent(event); // 调用基类的mouseMoveEvent以保持原有功能

}


bool MyCustomPlot::event(QEvent *event)
{
    if(event->type() == QEvent::TouchBegin
            || event->type() == QEvent::TouchUpdate
            || event->type() == QEvent::TouchEnd)
    {
//        qDebug()<<"event type = "<<event->type();
         return handleTouchEvent(static_cast<QTouchEvent *>(event));
    }
    return QCustomPlot::event(event);
}




bool MyCustomPlot::handleTouchEvent(QTouchEvent *event)
{
    if (event->touchPoints().count() == 2) { // 仅当有两个触摸点时处理缩放和移动
        const QPointF center = (event->touchPoints().at(0).pos() + event->touchPoints().at(1).pos()) / 2.0;
        const double distance = QLineF(event->touchPoints().at(0).pos(), event->touchPoints().at(1).pos()).length();
        switch (event->type()) {
        case QEvent::TouchBegin: {
            m_startDistance = distance;
            m_startCenter = center;
            break;
        }
        case QEvent::TouchUpdate: {
            QDateTime currentDateTime = QDateTime::currentDateTime();
            qint64 differenceInMSecs = qAbs(currentDateTime.msecsTo(CollectTimePre));
            if(differenceInMSecs > 200)
            {
                m_startDistance = distance;
            }
            else
            {
                const double scaleFactor = distance / m_startDistance;
                WheelShrinkView(m_startCenter,scaleFactor);
            }
            m_startCenter = center; // 更新起始中心点为当前中心点，以便下一次移动计算正确
            CollectTimePre = currentDateTime;
            break;
        }
        case QEvent::TouchEnd: {
            // 可以选择在这里做一些清理工作，如重置一些状态等
            break;
        }
        default:
            break;
        }
        return true; // 事件已处理，无需进一步传递
    }
    return false; // 让基类处理其他触摸事件或非触摸事件
}

void MyCustomPlot::contextMenuEvent(QContextMenuEvent *event)
{
    menu->exec(event->globalPos());
}

void MyCustomPlot::onActionTriggered1()
{
    shrinkView(0.9);
}

void MyCustomPlot::onActionTriggered2()
{
    shrinkView(1.1);
}

void MyCustomPlot::onActionTriggered3()
{

}

void MyCustomPlot::onActionTriggered4()
{

}

void MyCustomPlot::handlePinchGesture(QPinchGesture *gesture)
{
    // 处理捏合手势
    if (gesture->state() == Qt::GestureStarted) {
        // 开始捏合
    } else if (gesture->state() == Qt::GestureUpdated) {
        // 更新捏合状态
//        QPointF deltaPos = gesture->totalChange().scaleFactor();
        qreal scaleFactor = gesture->totalScaleFactor();

        xAxis->scaleRange(1 / scaleFactor, xAxis->range().center());
        yAxis->scaleRange(1 / scaleFactor, yAxis->range().center());

        this->replot();

        // 使用deltaPos来改变视图或进行其他操作
    } else if (gesture->state() == Qt::GestureFinished) {
        // 捏合结束
    }
}

void MyCustomPlot::shrinkView(double factor)
{
    // 获取当前轴的范围
    double xMin = xAxis->range().lower;
    double xMax = xAxis->range().upper;
    double yMin = yAxis->range().lower;
    double yMax = yAxis->range().upper;

    // 计算新的范围
    double xRange = xMax - xMin;
    double yRange = yMax - yMin;
    double newXMin = xMin + xRange * (1 - factor) / 2;
    double newXMax = xMax - xRange * (1 - factor) / 2;
    double newYMin = yMin + yRange * (1 - factor) / 2;
    double newYMax = yMax - yRange * (1 - factor) / 2;

    // 设置新的轴范围
    xAxis->setRange(newXMin, newXMax);
    yAxis->setRange(newYMin, newYMax);

    // 重新绘制图表
    replot();
}

void MyCustomPlot::WheelShrinkView(QPointF Center,double factor)
{

    // 创建一个模拟的滚轮事件
    // 使用第一个构造函数

    if(std::isinf(factor))
    {
        return;
    }

    QPoint  center = Center.toPoint();

    qDebug() << "factor:" << factor;
    int delta = 0;

    if(factor <= 0.45 )
    {
        delta = -60;
    }
    else if(factor > 0.45 && factor < 0.7  )
    {
        delta = -40;
    }
    else if( factor >= 0.7 && factor < 0.75 )
    {
        delta = -20;
    }
    else if( qFuzzyCompare( factor , 1.0))
    {
        return;
    }
    else if(factor >= 1.0 && factor < 1.25  )
    {
        delta = 20;
    }
    else if(factor >= 1.25 && factor < 1.7)
    {
        delta = 40;
    }
    else if(factor >= 1.7)
    {
        delta = 60;
    }

    qDebug() << " delta:" << delta;

    if(delta == 0)
        return;

    QWheelEvent event1(center, // pos
                       delta,              // delta
                       Qt::NoButton,     // buttons
                       Qt::NoModifier);  // modifiers

    QApplication::sendEvent(this, &event1);

}


void MyCustomPlot::RescaleAxes(double scaleFactor)
{
    // 根据scaleFactor缩放x轴和y轴，例如：
    xAxis->setRange(xAxis->range().center() - (xAxis->range().size() - xAxis->range().size() / scaleFactor) / 2.0, xAxis->range().size() / scaleFactor);
    yAxis->setRange(yAxis->range().center() - (yAxis->range().size() - yAxis->range().size() / scaleFactor) / 2.0, yAxis->range().size() / scaleFactor);
    replot(); // 重新绘制图表以应用缩放变化
}

void MyCustomPlot::MoveView(const QPointF &translation)
{
    // 根据translation移动视图，例如：
    xAxis->setRange(xAxis->range().center() + translation.x(), xAxis->range().size());
    yAxis->setRange(yAxis->range().center() + translation.y(), yAxis->range().size());
    replot(); // 重新绘制图表以应用移动变化
}

//void MyCustomPlot::mousePressEvent(QMouseEvent *event)
//{
//    if (event->button() == Qt::RightButton ) {
//        if(bSendXAxisData)
//            bSendXAxisData = false;
//    }
//     QWidget::mousePressEvent(event);
//}

//void MyCustomPlot::mouseReleaseEvent(QMouseEvent *event)
//{
//    // 检查是否是鼠标左键点击
//    if (event->button() == Qt::RightButton ) {
//        if(bSendXAxisData)
//            bSendXAxisData = false;
//        else
//        {
//            bSendXAxisData = true;
//            emit sig_XAxisCoordinates(xAxis->pixelToCoord(mLastX),mIndex);
//        }
//    }

//    // 调用父类的实现，以确保其他默认行为不会被覆盖
//    QWidget::mouseReleaseEvent(event);
//}
